import ntpath
import os
import zipfile
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import email.utils


def text(sender, receiver, cc_receivers, subject, msg, msg_type):
    message = MIMEText(msg, msg_type, 'utf-8')
    message['From'] = email.utils.formataddr((Header(sender, 'utf-8').encode(), sender))
    message['To'] = Header(",".join(receiver), 'utf-8')
    message['Cc'] = Header(",".join(cc_receivers), 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')
    return message


def get_path(path):
    if os.path.isfile(path):
        return path
    else:
        dir_name = ntpath.basename(path) + '.zip'
        zip_path = os.path.join(os.getcwd(), dir_name)
        if os.path.exists(zip_path):
            return zip_path
        z = zipfile.ZipFile(dir_name, 'w', zipfile.ZIP_DEFLATED)
        for dir_path, dir_names, filenames in os.walk(path):
            f_path = dir_path.replace(path, '')
            f_path = f_path and f_path + os.sep or ''
            for filename in filenames:
                z.write(os.path.join(dir_path, filename), f_path + filename)
        z.close()
        return zip_path


def enclosure(sender, receiver, cc_receivers, subject, msg, msg_type, filepath):
    message = MIMEMultipart()
    message['From'] = email.utils.formataddr((Header(sender, 'utf-8').encode(), sender))
    message['To'] = Header(",".join(receiver), 'utf-8')
    message['Cc'] = Header(",".join(cc_receivers), 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')
    message.attach(MIMEText(msg, msg_type, 'utf-8'))
    filepath = get_path(filepath)
    with open(filepath, 'rb') as f:
        file = f.read()
    attr = MIMEText(file, 'base64', 'utf-8')
    attr["Content-Type"] = 'application/octet-stream'
    filename = ntpath.basename(filepath)
    attr['Content-Disposition'] = f'attachment; filename="{filename}"'
    message.attach(attr)
    return message
